﻿using System.Collections.Generic;

namespace HCore
{
    public abstract class CommandManager
    {
        public Dictionary<int, List<TurnData>> turnMap => _turnMap;
        public Dictionary<int, string> serverProxies => _serverProxies;

        protected readonly HGame _game;
        private readonly TurnData _emptyTurnData;
        protected Dictionary<int, List<TurnData>> _turnMap;
        protected Dictionary<int, string> _serverProxies;

        public CommandManager(HGame game)
        {
            _game = game;
            _turnMap = new Dictionary<int, List<TurnData>>();
            _serverProxies = new Dictionary<int, string>();
            _emptyTurnData = new TurnData();
        }

        public abstract void AddUserCommand(Command command);

        public void AddTurnData(int turnCount, TurnData turnData)
        {
            int playerId = turnData.playerId;
            if (!_turnMap.TryGetValue(playerId, out var turnDatas))
            {
                turnDatas = new List<TurnData>();
                _turnMap.Add(playerId, turnDatas);
            }

            turnDatas.Add(turnData);
        }

        private TurnData GetTurnData(int playerId, int turnCount)
        {
            if (!_turnMap.TryGetValue(playerId, out var turnDatas))
            {
                return _emptyTurnData;
            }

            int index = turnCount - GameDefine.COMMAND_DELAY_TURN - 1;
            if (index < 0 || index >= turnDatas.Count)
            {
                return _emptyTurnData;
            }

            return turnDatas[index];
        }

        public bool CheckTurnData(int playerId, int turnCount)
        {
            int index = turnCount - GameDefine.COMMAND_DELAY_TURN - 1;
            if (index < 0)
            {
                return true;
            }

            if (!_turnMap.TryGetValue(playerId, out var turnDatas))
            {
                return false;
            }


            return index < turnDatas.Count;
        }

        public virtual void Update(int checkSum)
        {
            if (_game.timer.frameCount > 0 && _game.timer.frameCount % GameDefine.FRAMES_PER_TURN == 0)
            {
                foreach (var kv in _turnMap)
                {
                    TurnData turnData = GetTurnData(kv.Key, _game.timer.frameCount / GameDefine.FRAMES_PER_TURN);
                    turnData?.ProcessCommands(_game);
                } 
            }
        }

        public virtual void Dispose()
        {
            
        }
    }
}